package org.jbpm.pvm.internal.lob;

import java.sql.SQLException;

import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.jbpm.api.JbpmException;
import org.jbpm.pvm.internal.processengine.SpringProcessEngine;

/**
 * 
 * 重写的org.jbpm.pvm.internal.lob.BlobStrategyBlob<br />
 * <p>
 * 1. 重写了set()方法 重新实现了createBlob<br />
 * </p>
 * 
 * @author wstuo
 *
 */
public class BlobStrategyBlob implements BlobStrategy {
    
    private SessionFactory getSessionFactory() {
        return (SessionFactory) SpringProcessEngine.ctx.getBean("sessionFactory");
    }

    public void set(byte[] bytes, Lob lob) {
        if (bytes!=null) {
            lob.cachedBytes = bytes;
            
            SessionFactory sessionFactory = getSessionFactory();
            if (null != sessionFactory) {
            	lob.blob =  Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(bytes);
            }
        }
    }

    public byte[] get(Lob lob) {
        if (lob.cachedBytes!=null) {
            return lob.cachedBytes;
        }

        java.sql.Blob sqlBlob = lob.blob;
        if (sqlBlob!=null) {
            try {
                return sqlBlob.getBytes(1, (int) sqlBlob.length());
            } catch (SQLException e) {
                throw new JbpmException("couldn't extract bytes out of blob", e);
            }
        } 
        return null;
    }
}
